/*
    Copyright (C) 2010-2011 mdis
    
    This file is part of mdis.
    Written by Ketfi-Chérif Mehdi <ketficherif.mehdi@gmail.com>

    mdis is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    mdis is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with mdis.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "global.h"

char **
 misc_list_directory ( void )
{
	char **list = NULL;
	char *usr[] = {
		"/usr/local/share/mdis/plugins" ,
		"/usr/share/mdis/plugins" ,
		"/.mdis/plugins"
	};
	struct passwd * pwd = NULL;
	uint32_t hl = 0;
	if ( !(list = calloc ( DEFAULT_NPLUGINS_DIR , sizeof ( char *) )) )
		return NULL;
	if ( !(list[0] = calloc ( strlen ( usr[0] ) + 1 , sizeof ( char ) )) )
	{
		free ( list );
		return NULL;
	}
	if ( !(list[1] = calloc ( strlen ( usr[1] ) + 1 , sizeof ( char ) )) )
	{
		free ( list[0] );
		free ( list );
		return NULL;
	}
	if ( !(pwd = getpwuid ( getuid () )) )
	{
		switch ( errno )
		{
			case EINTR:
				break;

			case EIO:
				break;

			case EMFILE:
				break;

			case ENFILE:
				break;

			case ENOMEM:
				break;

			case ERANGE:
				break;
		}
		free ( list[1] );
		free ( list[0] );
		free ( list );
		return NULL;
	}
	hl = strlen ( pwd->pw_dir ) + strlen ( usr[2] ) + 1;
	if ( !(list[2] = calloc ( hl , sizeof ( char ) )) )
	{
		free ( list[1] );
		free ( list[0] );
		free ( list );
		return NULL;
	}
	snprintf ( list[0] , strlen ( usr[0] ) + 1 , "%s" , usr[0] );
	snprintf ( list[1] , strlen ( usr[1] ) + 1 , "%s" , usr[1] );
	snprintf ( list[2] , hl , "%s%s" , pwd->pw_dir , usr[2] );
	return list;
}

void
 misc_list_destroy ( char **list )
{
	uint8_t i;
	if ( list != NULL )
	{
		for ( i = 0; i < DEFAULT_NPLUGINS_DIR ; i++ )
		{
			if ( list[i] != NULL )
				free ( list[i] );
		}
		free ( list );
	}
}
